package com.cn.auth.jwt;

import com.cn.auth.jwt.signers.HmacSign;
import com.cn.auth.jwt.signers.Signature;
import com.cn.core.utils.DateUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import java.util.Date;


/**
 * @Author SHANGGUAN
 **/
@AllArgsConstructor
@Getter
public class Jwt implements Sign {

    /**
     * 时间检查 测试环境可以不开启
     */
    @Setter
    private boolean timeCheck;
    /**
     * 头部
     */
    private final JwtHeader header;
    /**
     * 负载
     */
    private final JwtPayLoad payLoad;

    @Setter
    private Signature signature;

    @Setter
    private String sign;

    protected Jwt(JwtHeader header, JwtPayLoad payLoad, boolean timeCheck) {
        this.header = header;
        this.payLoad = payLoad;
        signature = new HmacSign();
        this.timeCheck = timeCheck;
    }

    protected Jwt(JwtHeader header, JwtPayLoad payLoad) {
        this.header = header;
        this.payLoad = payLoad;
        signature = new HmacSign();
    }

    protected Jwt(JwtHeader header, JwtPayLoad payLoad, Signature signature) {
        this.header = header;
        this.payLoad = payLoad;
        this.signature = signature;
    }

    @Override
    public String generateSignatures() {
        String sign = signature.sign(header.encrypt(), payLoad.encrypt());
        return header.encrypt() + "." + payLoad.encrypt() + "." + sign;
    }

    @Override
    public boolean verify() {
        if (timeCheck) {
            Long exp = payLoad.getExp();
            Date date = new Date(exp);
            return DateUtils.isNotTimeExpires(new Date(), date) && signature.verify(header.encrypt(), payLoad.encrypt(), this.sign);
        }
        return signature.verify(header.encrypt(), payLoad.encrypt(), this.sign);
    }

}
